import asyncio
import ssl
import json


class EchoClientProtocol(asyncio.Protocol):
    def __init__(self, message, cp):
        self.message = message
        self.cp = cp

    def connection_made(self, transport):
        transport.write(self.message.encode())
        print(transport.get_extra_info('socket'))
        print('Data sent: {!r}'.format(self.message))

    def data_received(self, data):
        print('Data received: {!r}'.format(data.decode()))

    def connection_lost(self, exc):
        print('The server closed the connection')
        # print('Stop the event loop')
        # self.loop.stop()


class CatchProgress(object):
    def __init__(self, filename, metadata=None):
        self.filename = filename
        self.metadata = metadata
        pass

    def set_done(self):
        pass

    def get_undone(self):
        pass


class FileCatcher:
    def __init__(self, parallel):
        self.parallel = parallel
        # self.loop = asyncio.get_event_loop()
        # TODO

    @staticmethod
    def sslins():
        sslcontext = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
        sslcontext.load_cert_chain(certfile="cert.pem", keyfile="key.pem")
        return sslcontext

    def add(self, filename, sources):
        cp = CatchProgress(filename)
        loop = asyncio.get_event_loop()
        coros = []
        for source in sources:
            message = json.dumps({'file': 'README.md', 'offset': 0, 'size': 20})
            coros.append(loop.create_connection(lambda: EchoClientProtocol(message, cp), source[0], source[1],
                                                     ssl=self.sslins()))
        loop.run_until_complete(asyncio.wait(coros))
        # loop.run_until_complete(coros[0])
        loop.run_forever()
        loop.close()
        pass

    def start(self):
        pass

    def join(self):
        pass

    def cancel(self):
        pass

